<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="filters.name" placeholder="名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <org-unit-select v-model="filters.parentId" :org-unit-type="2" placeholder="请选择加盟商" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button v-if="canAddOrgUnit" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleAdd">注册店铺</el-button>
      <div style="margin-left: 3.125rem;">
        <el-checkbox v-for="col in dynamicColumn.orgUnits" v-model="col.show" class="filter-item" style="margin-left:10px;" @change="tableKey=tableKey+1">
          {{ col.name }}
        </el-checkbox>
      </div>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      border
      fit
      :height="tableHeight"
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="selsChange"
    >
      <el-table-column type="index" width="60" />
      <el-table-column prop="name" label="名称" min-width="180" />
      <el-table-column prop="parentName" label="加盟商" min-width="180" />
      <el-table-column prop="status" label="状态" width="80" :formatter="formatStatus" />
      <el-table-column prop="hideCloudMovie" label="隐藏云端剧本" width="140" :formatter="formatHideCloudMovie" />
      <el-table-column v-if="checkColumn('createTime')" prop="createTime" label="注册时间" width="180" />
      <el-table-column v-if="checkColumn('address')" prop="fullAddress" label="地址" width="400" :formatter="formatAddress" />
      <el-table-column v-if="checkColumn('operation')" label="操作" width="260" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.index, scope.row)">编辑</el-button>
          <el-button v-if="isAdmin && scope.row.status === 1" size="small" @click="online(scope.index, scope.row)">上线</el-button>
          <el-button v-if="isAdmin && scope.row.status === 0" size="small" @click="offline(scope.index, scope.row)">下线</el-button>
          <el-button size="small" @click="generateQrCode(scope.index, scope.row)">生成二维码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="filters.page" :limit.sync="filters.limit" @pagination="loadPageList" />

    <!--新增界面-->
    <el-dialog title="店铺信息" :visible.sync="addFormVisible" :close-on-click-modal="false" @close="addDialogClose">
      <el-form ref="addForm" :model="addForm" :label-width="formLabelWidth" :rules="addFormRules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off" />
        </el-form-item>
        <el-form-item label="隐藏云端剧本" prop="hideCloudMovie">
          <el-radio-group v-model="addForm.hideCloudMovie" style="margin: 0 3px;">
            <el-radio-button :label="0">显示</el-radio-button>
            <el-radio-button :label="1">隐藏</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <v-region v-model="addForm.address.addressCode" type="group" :town="true" @values="addressChange" />
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input v-model="addForm.address.detailAddress" auto-complete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="addLoading" @click="addSubmit">提交</el-button>
      </div>
      <div>
        <effect-scatter-map :chart-data="chartData" height="350px" />
      </div>
    </el-dialog>

    <el-dialog title="店铺二维码" :visible.sync="qrCodeVisible" :close-on-click-modal="false">
      <div class="qr-code-container">
        <qrcode :size="156" :text="qrContent" />
        <p>{{ qrInfo.name }}</p>
        <p>{{ qrInfo.address }}</p>
        <p>失效日期：{{ qrInfo.expiredTime }}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="qrCodeVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrgUnit, saveOrgUnit, modifyOrgUnit, offline, online } from '@/api/org-units'
import { shopQrCodeInfo } from '@/api/qr-code'
import waves from '@/directive/waves' // waves directive
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Qrcode from '@/components/qrcode'
import OrgUnitSelect from '../components/org-unit-select'
import EffectScatterMap from '@/components/EffectScatterMap'

export default {
  name: 'OrgUnits',
  components: { Pagination, Qrcode, OrgUnitSelect, EffectScatterMap },
  directives: { waves },
  data() {
    return {
      tableHeight: 260,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      sels: [], // 列表选中列
      filters: {
        page: 1,
        limit: 20,
        name: '',
        parentId: null
      },
      orderBy: {
        orderColumn: '',
        order: ''
      },

      qrCodeVisible: false,
      qrInfo: {
        name: '',
        address: '',
        expiredTime: ''
      },
      qrContent: '{}',

      // 新增界面是否显示
      addFormVisible: false,
      addLoading: false,
      addFormRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      // 新增界面数据
      recordId: '',
      addForm: {
        name: '',
        hideCloudMovie: null,
        address: {
          addressCode: {
            province: '',
            city: '',
            area: '',
            town: ''
          },
          detailAddress: ''
        }
      },
      chartData: [],
      addressSelected: {}
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'formLabelWidth', 'dynamicColumn']),
    canAddOrgUnit() {
      const roles = this.userInfo.roles || []
      return this.userInfo.orgUnitType === 2 && roles.indexOf('Manager') !== -1
    },
    isAdmin() {
      const roles = this.userInfo.roles || []
      return roles.indexOf('Admin') !== -1
    },
    addr() {
      if (this.addressSelected) {
        const { province, city, area, town } = this.addressSelected
        const p = province ? province.value : ''
        const c = city ? city.value : ''
        const a = area ? area.value : ''
        const t = town ? town.value : ''
        return p + c + a + t
      }
      return ''
    },
    detailAddress() {
      return (this.addForm.address && this.addForm.address.detailAddress) || ''
    },
    fullAddr() {
      return this.addr + this.detailAddress
    }
  },
  watch: {
    fullAddr: {
      handler() {
        this.locateAddress()
      }
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 220
    this.loadPageList()
  },
  methods: {
    formatAddress: function(row) {
      return row.address ? row.address.fullAddress : ''
    },
    formatStatus(row) {
      const st = parseInt(row.status)
      if (st === 0) {
        return '已上线'
      } else if (st === 1) {
        return '已下线'
      }
      return ''
    },
    formatHideCloudMovie(row) {
      const st = parseInt(row.hideCloudMovie)
      if (st === 0) {
        return '显示'
      } else if (st === 1) {
        return '隐藏'
      }
      return ''
    },
    checkColumn(col) {
      if (this.dynamicColumn.orgUnits.hasOwnProperty(col)) {
        return this.dynamicColumn.orgUnits[col].show
      }
      return true
    },
    addressChange(data) {
      this.addressSelected = data
      this.locateAddress()
    },
    locateAddress() {
      // 创建地址解析器实例
      const myGeo = new BMap.Geocoder()
      const thiz = this
      // 将地址解析结果显示在地图上，并调整地图视野
      myGeo.getPoint(this.fullAddr, function(point) {
        if (point) {
          thiz.chartData = [{
            name: '当前地址:' + thiz.fullAddr,
            value: [point.lng, point.lat]
          }]
        }
      })
    },
    loadPageList() {
      this.listLoading = true
      const param = { ...this.filters, ...this.orderBy }
      param.type = 1
      listOrgUnit(param).then(({ success, message, data }) => {
        this.listLoading = false
        if (success) {
          const { records, total } = data || {}
          if (records && records.length > 0) {
            for (let i = 0; i < records.length; ++i) {
              const item = records[i]
              if (item.address) {
                item.address.fullAddress = (item.address.addr || '') + (item.address.detailAddress || '')
              }
            }
          }
          this.list = records
          this.total = total
        } else {
          this.$message({
            message: message || '查询列表失败',
            type: 'error'
          })
        }
      }, () => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.filters.page = 1
      this.loadPageList()
    },
    sortChange({ prop, order }) {
      this.orderBy.orderColumn = prop
      this.orderBy.order = order
      this.handleFilter()
    },
    selsChange(sels) {
      this.sels = sels
    },
    // 显示新增界面
    handleAdd: function() {
      this.addFormVisible = true
      this.recordId = null
      this.addForm = {
        name: '',
        hideCloudMovie: 0,
        address: {
          addressCode: {
            province: '',
            city: '',
            area: '',
            town: ''
          },
          addr: '',
          detailAddress: ''
        }
      }
      this.chartData = []
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    resetAddFormAddressCode() {
      this.addForm.address.addressCode.province = ''
      this.addForm.address.addressCode.city = ''
      this.addForm.address.addressCode.area = ''
      this.addForm.address.addressCode.town = ''
    },
    handleEdit(index, row) {
      this.addFormVisible = true
      this.recordId = row.id
      this.addForm.name = row.name
      this.addForm.hideCloudMovie = row.hideCloudMovie
      if (row.address) {
        this.addForm.address.detailAddress = row.address.detailAddress
        if (row.address.addressCode) {
          this.addForm.address.addressCode.province = row.address.addressCode.province
          this.addForm.address.addressCode.city = row.address.addressCode.city
          this.addForm.address.addressCode.area = row.address.addressCode.area
          this.addForm.address.addressCode.town = row.address.addressCode.town
        } else {
          this.resetAddFormAddressCode()
        }
        if (row.address.lng && row.address.lat) {
          this.chartData = [{
            name: '当前地址',
            value: [row.address.lng, row.address.lat]
          }]
        } else {
          this.chartData = []
        }
      } else {
        this.addForm.address.detailAddress = ''
        this.resetAddFormAddressCode()
        this.chartData = []
      }
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    lng() {
      if (this.chartData && this.chartData.length > 0) {
        return this.chartData[0].value[0]
      }
    },
    lat() {
      if (this.chartData && this.chartData.length > 0) {
        return this.chartData[0].value[1]
      }
    },
    addDialogClose: function() {
      this.$refs['addForm'].resetFields()
      this.addForm.address.detailAddress = ''
      this.resetAddFormAddressCode()
      this.chartData = []
      this.addFormVisible = false
    },
    // 新增
    addSubmit: function() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true
            this.addForm.address.addr = this.addr
            this.addForm.address.lng = this.lng()
            this.addForm.address.lat = this.lat()
            if (this.recordId) {
              this.doEdit()
            } else {
              this.doAdd()
            }
          })
        }
      })
    },
    doAdd() {
      saveOrgUnit({ ...this.addForm, type: 1 }).then(({ success, message }) => {
        this.addLoading = false
        if (success) {
          this.$message({
            message: message || '提交成功',
            type: 'success'
          })
          this.$refs['addForm'].resetFields()
          this.addFormVisible = false
          this.loadPageList()
        } else {
          this.$message({
            message: message || '添加失败',
            type: 'error'
          })
        }
      }, () => {
        this.addLoading = false
      })
    },
    doEdit() {
      modifyOrgUnit(this.recordId, this.addForm).then(({ success, message }) => {
        this.addLoading = false
        if (success) {
          this.$message({
            message: message || '提交成功',
            type: 'success'
          })
          this.$refs['addForm'].resetFields()
          this.addFormVisible = false
          this.loadPageList()
        } else {
          this.$message({
            message: message || '添加失败',
            type: 'error'
          })
        }
      }, () => {
        this.addLoading = false
      })
    },
    online(index, row) {
      this.$confirm('确认店铺上线吗？', '提示', {}).then(() => {
        this.listLoading = true
        online(row.id).then(({ success, message }) => {
          this.listLoading = false
          if (success) {
            this.loadPageList()
          } else {
            this.$message({
              message: message || '操作失败',
              type: 'error'
            })
          }
        }, () => {
          this.listLoading = false
        })
      })
    },
    offline(index, row) {
      this.$confirm('确认店铺下线吗？', '提示', {}).then(() => {
        this.listLoading = true
        offline(row.id).then(({ success, message }) => {
          this.listLoading = false
          if (success) {
            this.loadPageList()
          } else {
            this.$message({
              message: message || '操作失败',
              type: 'error'
            })
          }
        }, () => {
          this.listLoading = false
        })
      })
    },
    generateQrCode(index, row) {
      this.qrCodeVisible = true
      shopQrCodeInfo(row.id).then(({ success, message, data }) => {
        if (success) {
          this.qrInfo.name = data.name
          this.qrInfo.address = (data.addr || '') + (data.detailAddress || '')
          this.qrInfo.expiredTime = data.expiredTime
          this.qrContent = JSON.stringify(data)
        } else {
          this.$message({
            message: message || '查询二维码信息失败',
            type: 'error'
          })
        }
      }, () => {
        this.qrCodeVisible = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.qr-code-container {
  text-align: center;
  img {
    display: inline-block;
  }
}
</style>
